home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9490 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Crash Proofing?
  5. Date: 11 Mar 1996 08:47:21 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4i1at9$p0t@umbc9.umbc.edu>
  8. References: <4hsfje$rbr@uwm.edu>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Peter J Kleczka <peterk@alpha2.csd.uwm.edu> wrote:
  13. |>     I'm new to C programing and am trying to re-write a program
  14. |> I did in pascal in C.  When I wrote the pascal program I got
  15. |> caught up in the details of getting the program to work and
  16. |> consequentially readability of the code and user-friendlyness
  17. |> suffered......
  18. |> 
  19. |>     The program I'm working on (below) works fine as long
  20. |> as the user enters an integer.....but it gets caught in an
  21. |> endless loop between the functions: firstmenu() and firstchoice()
  22. |> when I enter, say, 5.5 instead of an integer
  23. |> 
  24. |> it's unlikely that the user would enter anything but an integer
  25. |> when presented with integer choices...but I want to make the
  26. |> code uncrashable .....what can I do if anything to make it
  27. |> so that the program doesnt do wierd things if the user enters
  28. |> the wrong thing here?
  29.  
  30. [code deleted]
  31.  
  32. |> firstchoice(){ /* get users choice and branch to appropos function */
  33. |> 
  34. |> unsigned choice;
  35. |> 
  36. |> scanf ("%d", &choice);
  37.  
  38. [rest deleted]
  39.  
  40. Your code was long so I removed all but what I needed. First of all 'choice'
  41. is declared as an unsigned int, but you use the normal int specifier within
  42. scanf(). So I'd change %d to %u...Furthermore, don't even use scanf() at all.
  43. It's terrible in loops and you seem to have stumbled across this with the
  44. problem you're having. Instead grab the text with fgets() and then strip off
  45. what you need with sscanf(). This also makes for much easier and well written
  46. error checking capabilities.
  47.  
  48. Check up on the FAQ at rtfm.mit.edu which has complete details on other
  49. nasty things scanf() does and why other options are usually preferable.
  50. -- 
  51. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  52.  
  53. Jonas J. Schlein  (schlein@gl.umbc.edu)
  54.